package com.vxdata.utils.modules.pdf.aspose;


import com.vxdata.utils.modules.word.freemarker.WordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Map;
import java.util.UUID;

@Component
public class PdfServiceImpl {
    @Autowired
    private WordUtil wordUtil;
    @Autowired
    private Word2PdfUtil word2PdfUtil;
    @Value("${word2pdf.tmpPath}")
    private String tmpPath;

    /**
     * 生成pdf
     *
     * @param map              数据
     * @param response         返回流
     * @param templateFileName 模板名称
     */
    public void word2pdf(Map<String, Object> map, HttpServletResponse response, String templateFileName) {
        long start = System.currentTimeMillis();
        try {
            // word与pdf的随机文件名
            String tmpFile = tmpPath + File.separator + UUID.randomUUID().toString();
            String wordFileName = tmpFile + ".docx";
            String pdfFileName = tmpFile + ".pdf";
            // 生成word
            wordUtil.createWordLocal(map, templateFileName, wordFileName);
            // 生成pdf
            Boolean flag = word2PdfUtil.word2pdf(wordFileName, pdfFileName);

            if (flag) {
                byte[] buf = new byte[8 * 1024];
                int len = 0;
                try (InputStream is = new FileInputStream(pdfFileName); OutputStream os = response.getOutputStream();) {
                    while ((len = is.read(buf, 0, buf.length)) != -1) {
                        os.write(buf, 0, len);
                    }
                    os.flush();
                } finally {
                    try {
                        deleteFile(wordFileName);
                        deleteFile(pdfFileName);
                    } catch (Exception e) {
                    }
                }
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        long end = System.currentTimeMillis();
        System.out.println("pdf转换成功，共耗时：" + +(end - start) / 1000.0);
    }

    /**
     * 删除文件
     *
     * @param filePath 文件
     * @return
     */
    public static boolean deleteFile(String filePath) {
        boolean flag = false;
        File file = new File(filePath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }
        return flag;
    }
}
